package blogs.eidos.cloud.framework.core.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.bigdata.cloud.framework.common.api.HttpCodeEnum;
import net.bigdata.cloud.framework.common.api.Resp;
import net.bigdata.cloud.framework.constant.CoreConstant;
import net.bigdata.cloud.framework.core.annotation.AuthIgnore;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

import static net.bigdata.cloud.framework.constant.CoreConstant.AUTH_CODE;

/**
 * @author ： Eidos
 * @date ：Created in 2021/4/12
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Slf4j
public class PlatformAuthInterceptor implements HandlerInterceptor {


    @Resource
    private BeanFactory beanFactory;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = null;

        try {
            handlerMethod = (HandlerMethod) handler;
        } catch (Exception e) {
            response.setStatus(HttpCodeEnum.NOT_FOUND.getCode());
            return false;
        }

        Method method = handlerMethod.getMethod();

        AuthIgnore ignoreAuthMethod = method.getAnnotation(AuthIgnore.class);
        if (handler instanceof HandlerMethod && null != ignoreAuthMethod) {
            return true;
        }

        Map<String, String[]> parameterMap = request.getParameterMap();
        if (null == parameterMap) {
            response.setStatus(HttpCodeEnum.ACCESS_DENIED_ERROR.getCode());
            response.getWriter().print(JSONObject.toJSONString(Resp.failed(HttpCodeEnum.ACCESS_DENIED_ERROR)));
            return false;
        }

        if (!parameterMap.containsKey(CoreConstant.AUTH_CODE) || null == parameterMap.get(CoreConstant.AUTH_CODE) || parameterMap.get(CoreConstant.AUTH_CODE).length == 0) {
            response.setStatus(HttpCodeEnum.ACCESS_DENIED_ERROR.getCode());
            response.getWriter().print(JSONObject.toJSONString(Resp.failed(HttpCodeEnum.ACCESS_DENIED_ERROR)));
            return false;
        }

        String authCode = parameterMap.get(AUTH_CODE)[0];
        if (StringUtils.isEmpty(authCode)) {
            response.setStatus(HttpCodeEnum.ACCESS_DENIED_ERROR.getCode());
            response.getWriter().print(JSONObject.toJSONString(Resp.failed(HttpCodeEnum.ACCESS_DENIED_ERROR)));
            return false;
        }
        return true;
    }
}
